import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.by import By
from util.chaojiying import get_points_img

service = webdriver.ChromeService('./chromedriver.exe')
driver = webdriver.Chrome(service=service)

driver.get('https://www.bilibili.com/')
driver.execute_script('''
(function() {
    // 创建小红点元素
    const dot = document.createElement('div');
    dot.style.cssText = `
        position: fixed;
        width: 10px;
        height: 10px;
        background: red;
        border-radius: 50%;
        pointer-events: none;
        z-index: 99999999999999999999999999;
        display: none;
    `;
    document.body.appendChild(dot);

    // 鼠标移动事件
    let timeout;
    document.addEventListener('mousemove', function(e) {
        // 显示小红点
        dot.style.display = 'block';
        dot.style.left = e.clientX - 5 + 'px';
        dot.style.top = e.clientY - 5 + 'px';

        // 清除之前的定时器
        clearTimeout(timeout);

        // 1秒后隐藏小红点
        timeout = setTimeout(() => {
            dot.style.display = 'none';
        }, 1000);
    });

    // 鼠标离开页面时隐藏
    document.addEventListener('mouseleave', function() {
        dot.style.display = 'none';
    });
})();
''')
login_button = driver.find_element(By.XPATH, '//div[@class="header-login-entry"]')
login_button.click()
time.sleep(1)
username_input = driver.find_element(By.XPATH, '//input[@placeholder="请输入账号"]')
username_input.send_keys('15225989853')
password_input = driver.find_element(By.XPATH, '//input[@placeholder="请输入密码"]')
password_input.send_keys('zdz123123')
time.sleep(1)
login_div = driver.find_element(By.XPATH, '//div[@class="btn_primary "]')
login_div.click()
time.sleep(2)
yzm_img = driver.find_element(By.XPATH, '//div[@class="geetest_widget"]')
yzm_img.screenshot('./static/yzm/bilibili.png')
size = yzm_img.size
ac = ActionChains(driver)
with open('./static/yzm/bilibili.png', 'rb') as f:
    img_bytes = f.read()
points = get_points_img(img_bytes, 9004)
for i in points['pic_str'].split('|'):
    x, y = i.split(',')
    ac.move_to_element_with_offset(yzm_img, int(x) - size['width'] / 2, int(y) - size['height'] / 2).pause(2).click()

ac.perform()
yzm_subim = driver.find_element(By.XPATH, '//a[@class="geetest_commit"]')
yzm_subim.click()

input()
driver.quit()

# {'err_no': 0, 'err_str': 'OK', 'pic_id': '1306611122095810005', 'pic_str': '158,102|174,213|240,254', 'md5': 'b5526c684fbffba90f2f4e11d18bb651'}
